<template>
  <el-upload
      class="img-upload"
      ref="upload"
      action
      accept="image/png,image/gif,image/jpg,image/jpeg"
      :http-request="handleUpload"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="handleSuccess"
      :before-upload="handleBeforeUpload"
      multiple
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList">
    <el-button slot="trigger" size="small" type="primary">上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传image/png, image/gif, image/jpg, image/jpeg的图片，且不超过2M</div>
  </el-upload>
</template>

<script>
export default {
  name: 'ImgUpload',
  data() {
    return {
      fileList: [],
      url: ''
    }
  },
  methods: {
    handleBeforeUpload(file) {
      if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
        this.$notify.warning({
          title: '警告',
          message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
        })
      }
      let size = file.size / 1024 / 1024 / 2
      if (size > 2) {
        this.$notify.warning({
          title: '警告',
          message: '图片大小必须小于2M'
        })
      }
    },
    // eslint-disable-next-line no-unused-vars
    handleRemove(file, fileList) {
    },
    handleUpload(params) {
      this.getBase64(params.file).then(response => {
        console.log(response);
        this.$axios.post('/api/library/covers', {
          imgResult: response,
          fileName: params.file.name
        }).then((res) => {
          this.url = res.data.data.data.imgUrl
          // console.log(res)
          this.$emit('onUpload')
          this.$message.warning('上传成功')
        });
      });
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = '';
        reader.readAsDataURL(file);
        reader.onload = function () {
          fileResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(fileResult);
        };
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // eslint-disable-next-line no-unused-vars
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleSuccess(response) {
      this.url = response
      this.$emit('onUpload')
      this.$message.warning('上传成功')
    },
    clear() {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style scoped>

</style>
